<template>
  <Row>
    <Form
      :model="addForm"
      :label-width="120"
      :rules="addFormRules"
      ref="addFormRef"
    >
      <Col :span="12">
        <FormItem label="城市：" prop="cityId">
          <Select
            v-model="addForm.cityId"
            placeholder="选择所属城市"
            :disabled="isEdit"
          >
            <Option
              v-for="item in cityList"
              :key="item.index"
              :label="item.name"
              :value="item.id"
            />
          </Select>
        </FormItem>
        <FormItem label="企业名称：" prop="name">
          <Input
            v-model="addForm.name"
            placeholder="请输入企业名称..."
            clearable
          />
        </FormItem>
        <FormItem label="企业别名：" prop="alias">
          <Input
            v-model="addForm.alias"
            placeholder="请输入企业别名..."
            clearable
          />
        </FormItem>
        <FormItem label="变压器配电结构：" prop="transformerStructure">
          <RadioGroup v-model="addForm.transformerStructure">
            <Radio value="true" label="true" :disabled="isEdit">是</Radio>
            <Radio value="false" :disabled="isEdit" label="false">否</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="所属行业" prop="businessId">
          <Select v-model="addForm.businessId" placeholder="请选择行业">
            <Option
              v-for="item in tradeList"
              :key="item.index"
              :label="item.name"
              :value="item.id"
            />
          </Select>
        </FormItem>
        <FormItem label="地址：" prop="address">
          <Input
            v-model="addForm.address"
            @on-blur="getLngLat"
            @on-change="addressChanage"
            placeholder="请输入地址..."
            clearable
          />
        </FormItem>
        <FormItem label="联系人：" prop="contactName">
          <Input
            v-model="addForm.contactName"
            placeholder="联系人姓名..."
            clearable
          />
        </FormItem>
        <FormItem label="联系电话：" prop="contactPhone">
          <Input
            v-model="addForm.contactPhone"
            placeholder="联系人电话..."
            clearable
          />
        </FormItem>
      </Col>
      <Col :span="12">
        <FormItem label="电量计算周期" prop="powerPeriod">
          <Select v-model="addForm.powerPeriod" placeholder="选择电量计算周期">
            <Option
              v-for="item in cycle"
              :key="item"
              :label="item"
              :value="item"
            />
          </Select>
        </FormItem>
        <FormItem
          label="主变容量"
          prop="mainTotal"
          v-if="addForm.transformerStructure === 'true'"
        >
          <Input
            v-model="addForm.mainTotal"
            placeholder="请输入主变容量..."
            clearable
          >
            <span slot="append">KVA</span>
          </Input>
        </FormItem>
        <FormItem
          label="主变台数"
          prop="mainCapacity"
          v-if="addForm.transformerStructure === 'true'"
        >
          <Input
            v-model="addForm.mainCapacity"
            placeholder="请输入主变台数..."
            clearable
          >
            <span slot="append">台</span></Input
          >
        </FormItem>
        <FormItem label="平安短信">
          <Row>
            <Col :span="6" style="margin-bottom:5px;">
              <i-switch v-model="safeOpen" size="large">
                <span slot="open">开启</span>
                <span slot="close">关闭</span>
              </i-switch>
            </Col>
            <transition name="fade">
              <Col :span="24" v-if="safeOpen">
                <Select v-model="safeTime" :filterable="false">
                  <Option
                    v-for="item in timeList"
                    :value="item"
                    :key="item"
                    :label="item"
                  ></Option>
                </Select>
              </Col>
            </transition>
          </Row>
        </FormItem>
        <FormItem label="系统功能">
          <RadioGroup v-model="addForm.sysFunc">
            <Radio :label="1">平台采集</Radio>
            <Radio :label="2">阿里Iot</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="其他功能" prop="func" v-if="addForm.sysFunc === 1">
          <CheckboxGroup v-model="addForm.func">
            <Checkbox label="thermalImager">热成像</Checkbox>
            <Checkbox label="humitureState">温湿度</Checkbox>
          </CheckboxGroup>
        </FormItem>
        <FormItem label="企业渠道" prop="channelId">
          <Select v-model="addForm.channelId" placeholder="请选择企业渠道">
            <Option
              v-for="item in channelList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </Select>
        </FormItem>
      </Col>
    </Form>
  </Row>
</template>

<script>
import {
  addForm,
  addFormRules,
  transStringToBoolean,
  buildFunc,
  funcBuild,
  booleanToString
} from "./material";
import {
  getCompanyDetailByCompanyId,
  getCityListOfNew,
  addCompany,
  editCompany,
  getTrade,
  getCompanyChannel
} from "@/api";

export default {
  props: {
    row: Object,
    isEdit: {
      type: Boolean,
      default: false
    }
  },

  mounted() {
    this.getCompanyChannel();
    this._getCityList();
    this.getTradeList();
    if (!!this.isEdit) {
      this.isEditInit();
    }
  },

  data() {
    return {
      cityList: [],
      addForm: JSON.parse(JSON.stringify(addForm)),
      addFormRules: { ...addFormRules },
      cycle: [...Array(24)].map((t, i) => `${++i}:00`),
      tradeList: [],
      safeOpen: false,
      timeList: [...Array(24)].map((t, i) => `${++i}:00`),
      safeTime: "1:00",
      selectRow: {},
      channelList: []
    };
  },

  methods: {
    // 获取城市列表
    _getCityList() {
      let vm = this;
      return new Promise((resolve, reject) => {
        getCityListOfNew().then(res => {
          if (res.code == 200) {
            vm.cityList = res.data;
            resolve();
          }
        });
      });
    },
    // async getCompanyInfo() {
    //   const { id } = this.row
    //   if (this.isEditInit) {
    //     if (id) {
    //       const response = await getCompanyDetailByCompanyId(id)
    //       if (response.code === 200) {
    //         this.selectRow = response.data
    //       }
    //     }
    //   }
    // },
    getCompanyChannel() {
      // const { id } = this.row
      // const params = { id }
      getCompanyChannel().then(res => {
        if (res.code === 200) {
          this.channelList = res.data;
        } else {
          this.channelList = [];
        }
      });
    },
    getTradeList() {
      getTrade().then(res => {
        if (res.code === 200) {
          this.tradeList = res.data;
        }
      });
    },

    addressChanage() {
      const vm = this;
      vm.addForm.lng = null;
      vm.addForm.lat = null;
    },

    // 如果是编辑，初始化表单数据
    isEditInit() {
      const vm = this,
        params = { ...vm.row, func: [] };
      params.func = funcBuild(params);
      params.transformerStructure = booleanToString(
        params.transformerStructure
      );
      if (params.safeAlertPeriod) {
        vm.safeTime = params.safeAlertPeriod;
        vm.safeOpen = true;
      }

      delete params.humitureState;
      delete params.thermalImager;
      vm.addForm = { ...params };
    },

    // 编辑保存
    submitEdit() {
      const vm = this;
      let {
        cityId,
        name,
        alias,
        address,
        contactName,
        contactPhone,
        lng,
        lat,
        transformerStructure,
        powerPeriod,
        mainTotal,
        mainCapacity,
        func,
        id,
        businessId,
        channelId
      } = vm.addForm;
      let params = {
        cityId,
        name,
        alias,
        address,
        contactName,
        contactPhone,
        lng,
        lat,
        transformerStructure,
        powerPeriod,
        id,
        businessId,
        channelId
      };
      if (vm.safeOpen) {
        params.safeAlertPeriod = vm.safeTime;
      }

      params.transformerStructure = transStringToBoolean(
        params.transformerStructure
      );
      buildFunc(params, func);
      if (params.transformerStructure) {
        params["mainTotal"] = mainTotal;
        params["mainCapacity"] = mainCapacity;
      }
      editCompany(params).then(res => {
        if (res.code == 200) {
          vm.$Message.success("更新企业信息成功");
          setTimeout(() => {
            vm.$emit("save", false);
          }, 500);
        } else {
          vm.$Message.error(res.message);
          vm.$emit("btnDisable", false);
        }
      });
    },

    // 获取经纬度
    getLngLat(e) {
      let self = this;
      let address = e.target.value;
      this.$jsonp("http://api.map.baidu.com/geocoder/v2/", {
        address,
        output: "json",
        ak: "GUW9ADvtjdH1TIxkcSkXx2LrNLoQrGEy"
      })
        .then(json => {
          self.addForm.lng = json.result.location.lng;
          self.addForm.lat = json.result.location.lat;
        })
        .catch(err => {});
    },

    // 新增保存
    submitAddNew() {
      const vm = this;

      let {
        cityId,
        name,
        alias,
        address,
        contactName,
        contactPhone,
        lng,
        lat,
        transformerStructure,
        powerPeriod,
        mainTotal,
        mainCapacity,
        businessId,
        func,
        sysFunc,
        channelId
      } = vm.addForm;
      let params = {
        cityId,
        name,
        alias,
        address,
        contactName,
        contactPhone,
        lng,
        lat,
        transformerStructure,
        powerPeriod,
        mainTotal,
        businessId,
        mainCapacity,
        sysFunc,
        channelId
      };
      if (vm.safeOpen) {
        params.safeAlertPeriod = vm.safeTime;
      }

      params.transformerStructure = transStringToBoolean(
        params.transformerStructure
      );
      buildFunc(params, func);
      addCompany(params).then(res => {
        if (res.code == 200) {
          vm.$Message.success("新建企业成功");
          setTimeout(() => {
            vm.$emit("save", false);
          }, 500);
        } else {
          vm.$emit("btnDisable", false);
          vm.$Message.error(res.message);
        }
      });
    },

    // 提交
    submit() {
      const vm = this;
      vm.$refs.addFormRef.validate(valid => {
        if (valid) {
          vm.$emit("btnDisable", true);
          if (vm.isEdit) {
            vm.submitEdit();
          } else {
            vm.submitAddNew();
          }
        }
      });
    }
  }
};
</script>
